//<%@ page pageEncoding="UTF-8"%>
////////////////////以下是业务无关的///////////////////
var ____________________________________;

var Js = {};

Js.getObjType = function(objClass){
	if ( objClass && objClass.constructor ){
		var strFun = objClass.constructor.toString();
		var className = strFun.substr(0, strFun.indexOf('('));
		className = className.replace('function', '');
		return className.replace(/(^\s*)|(\s*$)/g, ""); 
	}
	return typeof(objClass);
}

/*
 * 用法: function Fruit(){}; function Apple(){}; Js.extend(Apple,Fruit);   
 */
Js.extend = function(Child, Parent) {
	var parent = new Parent();
	Child.prototype = parent;
	Child.prototype.constructor = Child;
	Child.uber = Parent.prototype;

}

Js.json2str = function(o) {
	
	function fmt(s) {
		if (typeof s == 'object' && s != null) {
			return Js.json2str(s);
		}
		if ((typeof s) == 'string') {
			return '"' + (s.replace('"', '\\"')) + '"';
		} else if ((typeof s) == 'number') {
			return s;
		}
		return 'null';
	}
	
	if(o.length>=0 && typeof o.slice=='function'){
		var arr = [];
		for(var i=0;i<o.length;i++){
			arr.push(fmt(o[i]));
		}
		return '[' + arr.join(',') + ']';
	}else{
		var arr = [];
		for (var name in o){
			arr.push('"' + name + '":' + fmt(o[name]));
		}
		return '{' + arr.join(',') + '}';
	}
}

Js.str2json = function(str) {
	var jsObj = eval("("+str+")");
	return jsObj;
}

Js.json2list = function(json) {
	if(!json || json['#']!='L'){
		return json;
	}
	var objList = [];
	var ppList = json.p;
	var valList = json.v;
	var obj = null;
	for(var i=0;i<valList.length;i++){
		var pIndex = i % ppList.length;
		var pp = ppList[pIndex];
		var pv = valList[i];
		if(pIndex==0){
			obj = new Object();
			objList.push(obj);
		}
		obj[pp] = Js.json2list(pv);
	}
	return objList;
}


Js.delayExec = function(fun, timeout){
	var args = [];
	for(var i=2;i<arguments.length;i++){
		args[i-2] = arguments[i];
	}
	var f = function(){ 
		fun.apply(window, args);
	}
	var handle = setTimeout(f, timeout);
	return handle;
}

Js.log = function(str){
	var caller = Js.log.caller;
	if(typeof(console)=='undefined' || typeof(console.log)=='undefined'){
		window.title = str;
		return;
	}
	console.log(str);
}

Js.expand = function(obj, beautifier, level){
	var ws = '\n';
	level = level||0;
	for(var i=0;beautifier && i<level;i++){
		ws += '    ';
	}
	if((typeof obj) == 'string') {
		return '"' + (obj.replace('"', '\\"')) + '"';
	} else if((typeof obj) == 'number') {
		return obj;
	}
	
	if(typeof obj === 'function'){
		return obj;
	}
	
	//array
	if(obj.length>=0 && typeof obj.slice=='function'){
		var arr = [];
		for(var i=0;i<obj.length;i++){
			arr.push(Js.expand(obj[i], beautifier, level+1));
		}
		return '[' + arr.join(',') + ']';
	}else if(typeof obj == 'object' && obj != null) {
		var arr = [];
		for(name in obj){
			var v = obj[name];
			var vStr = Js.expand(v, beautifier, level+1);
			if(beautifier){
				vStr+=ws;
			}
			arr.push(ws+'"' + name + '":' + vStr);
		}
		return '{' + arr.join(',') + '}';
	}
	
}
//alert(Js.expand({a:[1,2,3],b:{b1:1}, c:function(){}},true,3));

//字符串工具类
var StringUtil = {}

StringUtil.getVariable = function(str){
	var v = str.substr(0,1).toLowerCase();
	v += str.substr(1);
	return v;
}

StringUtil.parseUrl = function(url){
	var fields = {
		'scheme' : 2,
		'username' : 4,
		'password' : 5,
		'port' : 7,
		'host' : 6,
		'path' : 8,
		'query' : 9,
		'fragment' : 10
	};
	var regex = /^((\w+):\/\/)?((\w+):?(\w+)?@)?([^\/\?:]+):?(\d+)?(\/?[^\?#]+)?\??([^#]+)?#?(\w*)/;
	var group = regex.exec(url);
	var uri = {};
    for(var name in fields){
    	var index = fields[name];
    	uri[name] = group[index];
    	//alert(name+':'+uri[name]);
    }
    return uri;
}

//var url = 'http://user:password@www.jb51.net:1234/test/test.asp?id=1#test';
//StringUtil.parseUrl(url);

StringUtil.getFileName = function(path){
	if(!path){
		return path;
	}
	var pos1 = path.lastIndexOf('/')||-1;
	var pos2 = path.lastIndexOf('\\')||-1;
	var pos = Math.max(pos1, pos2);
	if(pos==-1){
		return path;
	}
	var fileName = path.substr(pos+1);
	return fileName;
}

StringUtil.getRandomString=function(){
	var date = new Date();
	var str = ''+date.getTime()+'-';
	for(var i=0;i<5;i++){
		str+=Math.floor(Math.random()*10);
	}
	return str;
}

/* 格式化日期 */
StringUtil.getFormatDate = function(date, size) {
	var lpad=function(str){
		return StringUtil.leftPad(str, 2, '0');
	}
	date = date || new Date();
	size = size || 19;
	var dateStr = '';
	dateStr = lpad(date.getFullYear()) + "-" + lpad(date.getMonth()+1) + "-"
			+ lpad(date.getDate()) + " " + lpad(date.getHours()) + ":" + lpad(date.getMinutes())
			+ ":" + lpad(date.getSeconds()) + ' ' + lpad(date.getMilliseconds());
	dateStr = dateStr.substr(0, size);
	return dateStr;
}

/* 格式化文件长度 */
StringUtil.formatFilesize=function(size){
	var len = size;
	var K = 1024;
	var M = K * 1024;
	if(len>=M){
		var n = len/M;
		var i = Math.floor(n);
		var d = n - i;
		
		var str=''+i;
		str += ('.'+Math.round(d*100)).substr(0,3);
		return str+'M';
	}
	if(len>=K){
		var n = len/K;
		var i = Math.floor(n);
		var d = n - i;
		
		var str=''+i;
		str += ('.'+Math.round(d*100)).substr(0,3);
		return str+'K';
	}
	return ''+len+'字节';
}

StringUtil.leftPad = function(str, minLength, filling) {
	str = ''+str;
	filling = filling||' ';
    var ln = str.length;
    if (minLength <= ln) {
        return str;
    }
    
    var res = '';
    
    var dif = minLength - ln;
    for (var i = 0; i < dif; i++) {
    	res += filling;
    }
    
    res += str;
    
    return res;
}


/* 文本在html中的表示 */
StringUtil.htmlEncode=function(text){
	text = text.replace(/&/g,	"&amp;") ;
	text = text.replace(/"/g,	"&quot;") ;
	text = text.replace(/</g,	"&lt;") ;
	text = text.replace(/>/g,	"&gt;") ;
	//text = text.replace(/'/g,	"&#146;") ;
	text = text.replace(/\ /g,	"&nbsp;");
	text = text.replace(/\n/g,	"<br>");
	text = text.replace(/\t/g,	"&nbsp;&nbsp;&nbsp;&nbsp;");
	return text;
}

StringUtil.htmlDecode=function(s){
	s = s.replace(/&lt;/gi,"<");
	s = s.replace(/&gt;/gi,">");
	s = s.replace(/&quot;/gi,"\"");
	s = s.replace(/&amp;/gi,"&");
	s = s.replace(/&nbsp;/gi," ");
	s = s.replace(/<\/div>/ig, "\n");
	s = s.replace(/<\/p>/ig, "\n");
	s = s.replace(/<br*.>/ig, "\n");
	return s;
}

StringUtil.getUrlParamMap=function(qstr){
	var result = {};
    var reg = new RegExp("(?:^|&)([^=&'\"]+)=([^&]*)", "g");
    var group;
    while((group=reg.exec(qstr))!=null){
    	result[group[1]] = unescape(group[2]);
    }
	return result;
}

StringUtil.getUrlParamStr=function(map){
	var params = '';
	for(var name in map){
		params += name+'='+map[name]+'&';
	}
	if(params.length>0){
		return params.substr(0, params.length-1);
	}else{
		return params;
	}
}

StringUtil.startsWith=function(str, prefix, toffset){
	var value = str;
    var ta = value;
    var to = toffset;
    var pa = prefix;
    var po = 0;
    var pc = prefix.length;
    // Note: toffset might be near -1>>>1.
    if ((toffset < 0) || (toffset > value.length - pc)) {
        return false;
    }
    while (--pc >= 0) {
        if (ta[to++] != pa[po++]) {
            return false;
        }
    }
    return true;
}

StringUtil.endsWith=function(str, suffix){
	return StringUtil.startsWith(str, suffix, str.length - suffix.length);
}

function $E(id){
	return document.getElementById(id);
}

var DomUtil = {};

DomUtil.getElementStyle = function(el,attr){
	if(el.currentStyle){
		return el.currentStyle[attr];
	}else if(window.getComputedStyle){
		return window.getComputedStyle(el,null).getPropertyValue(attr);
	}
	return null;
}

DomUtil.isSuper = function(parent, element){
	var b = document.body;
	var de = document.documentElement;
	if(parent==b||parent==de){
		return true;
	}
	var p = element;
	while((p = p.parentNode) != null){
		if(p==b||p==de){
			break;
		}
		if(p==parent){
			return true;
		}
	}
	return false;
}

DomUtil.getSuper = function(element, pname, pvalue){
	if(!pname){
		return element.parentNode;
	}
	
	var parent = element;
	if(!pvalue){
		var tag = pname;
		while((parent = parent.parentNode) != null){
			if(parent.tagName==tag){
				return parent;
			}
		}
	}else{
		while((parent = parent.parentNode) != null){
			if(parent.getAttribute(pname)==pvalue){
				return parent;
			}
		}
	}

	return null;
}

DomUtil.findByClass = function(element, clazName, elementArray){
	var tName = ' '+clazName+' ';
	var children = element.childNodes;
	elementArray = elementArray||[];
	for(var i=0;i<children.length;i++){
		if(children[i].nodeType==1){
			var ce = children[i];
			var cs = ' '+ce.getAttribute('class')+' ';
			if(cs.indexOf(tName)!=-1){
				elementArray.push(ce);
			}
			DomUtil.findByClass(ce, clazName, elementArray);
		}
	}
	return elementArray;
}

DomUtil.setStyle = function(element, styles){
	for(name in styles){
		var v = styles[name];;
		var s = name;
		var sa = s.split('-');
		s = sa[0];
		for(var i=1;i<sa.length;i++){
			s += sa[i].charAt(0).toUpperCase();
			s += sa[i].substr(1);
		}
		element.style[s] = v;
	}
}

DomUtil.getChild = function(element, pname, pvalue){
	var ea = DomUtil.getChildren(element, pname, pvalue);
	if(ea.length>0){
		return ea[0];
	}
	return null;
}

DomUtil.getText = function(element){
	var text = element.text||element.textContent||element.innerText;
	return text;
}

DomUtil.getChildren = function(element, pname, pvalue){
	var children = element.childNodes;
	var elementArray = [];
	for(var i=0;i<children.length;i++){
		if(children[i].nodeType==1){
			var ce = children[i];
			if(pname && pvalue){
				if(ce.getAttribute(pname)==pvalue||ce[pname]==pvalue){
					elementArray.push(ce);
				}
			}else{
				elementArray.push(ce);
			}
		}
	}
	return elementArray;
}

DomUtil.removeChildren = function(element, start){
	start = start||0;
	var children = DomUtil.getChildren(element);
	for(var i=children.length-1; i>=start; i--){
		element.removeChild(children[i]);
	}
}

DomUtil.removeElement = function(element){
	if(!element || !element.parentNode){
		return element;
	}
	return element.parentNode.removeChild(element);
}

DomUtil.newElement = function(tagName, attrJson, parent){
	var element = document.createElement(tagName);
	if(attrJson!=null){
		for(var name in attrJson){
			element.setAttribute(name, attrJson[name]);
		}
	}
	if(parent){
		if(typeof(parent)=='string'){
			parent = document.getElementById(parent);
		}
		parent.appendChild(element);
	}
	return element;
}

/**
 * 取得事件触发的位置（相对于目标元素）
 */
DomUtil.getOffset = function(event, element) {
	event = window.event||event;
	var pos = {};
	
	pos.clientX = event.clientX;
	pos.clientY = event.clientY;
	
	if (event.offsetX) {
		pos.offsetX = event.offsetX;
		pos.offsetY = event.offsetY;
	} else {
		var target = element||event.currentTarget; // 当前触发的目标对象
		var epos = DomUtil.getElementAbsPos(target, true);
		pos.offsetX = event.clientX - epos.left;
		pos.offsetY = event.clientY - epos.top;
	}
	
	return pos;
}

/*
 * 取得元素(static定位)的绝对坐标
 * isClient 是：相对于浏览器显示区；否：相对于网页区域（包括因滚动隐藏的部分）
 */
DomUtil.getElementAbsPos = function(element, isClient) {
    var t = 0;
    var l = 0;
    while(element) {
    	var parent = element.offsetParent;
    	if(isClient && parent){
    		t -= parent.scrollTop;
    		l -= parent.scrollLeft;
    	}
        t += element.offsetTop;
        l += element.offsetLeft;
    	element = parent;
    }
    return {left:l, top:t};
}

DomUtil.recursive = function(element, filter){
	var r = filter(element);
	if(r){
		return ;
	}
	var children = element.childNodes;
	for(var i=0;i<children.length;i++){
		var child = children[i];
		DomUtil.recursive(child, filter);
	}
}

DomUtil.getWindowScrollPosition = function(){
	var doc = document.documentElement;
	var left = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0);
	var top = (window.pageYOffset || doc.scrollTop)  - (doc.clientTop || 0);
	return {left:left, top:top};
}

DomUtil.elementFromPoint = function(x, y) {
	var bi = Browser.getInfo();
	if(bi.name=='opera'||bi.name=='safari'){
		var scroll = this.getWindowScrollPosition();
		x += scroll.left;
		y += scroll.top;
	}
	return this.document.elementFromPoint(x, y);
}

DomUtil.elementsFromPoint = function(x, y) {
	var list = [];
	var filter = function(element){
		if(element.nodeType==1){
			var elementPos = DomUtil.getElementAbsPos(element, true);
			if(x>=elementPos.left && x<=(elementPos.left+element.offsetWidth) && y>=elementPos.top && y<=(elementPos.top+element.offsetHeight)){
				list.push(element);
			}
		}
		return false;
	}
	
	DomUtil.recursive(document.body, filter);
	return list;
}

DomUtil.imgsFromPoint = function(x, y) {
	if(!y){
		var event = x;
		x = event.clientX;
		y = event.clientY;
	}
	var imgs = [];
	var reg = /url\(["']?(.*)['"]?\)/;
	var list = DomUtil.elementsFromPoint(x, y);
	for(var i=0;i<list.length;i++){
		var element = list[i];
		if(element.tagName=='IMG'){
			var img = {};
			img.type = 'img';
			img.element = element;
			imgs.push(img);
		}else{
			var bgSrc = DomUtil.getElementStyle(element, 'background-image');
			if(bgSrc && bgSrc!='none'){
				var img = {};
				img.type = 'bg';
				img.element = element;
				img.bg = bgSrc.replace(reg, '$1');
				imgs.push(img);
			}
		}
	}
	return imgs;
}

var Win = {}

Win.width = function(){
	return Math.max(document.body.scrollWidth,document.documentElement.scrollWidth);
}

Win.height = function(){
	var _scrollHeight=0;
    _scrollHeight = Math.max(document.body.scrollHeight,document.documentElement.scrollHeight);
	_scrollHeight = Math.max(_scrollHeight,document.documentElement.clientHeight);
	return _scrollHeight;
}

Win.scrollTop = function(){
  return Math.max(document.body.scrollTop, document.documentElement.scrollTop);
}

Win.scrollLeft = function(){
  return Math.max(document.body.scrollLeft, document.documentElement.scrollLeft);
}

/* 滚屏 */
Win.scrollScreen = function(win){
	win.scroll(0,65000);
}

/* 滚动层 */
Win.scrollLayer = function(layer){
	layer.parentNode.scrollTop = layer.offsetHeight;
}

/******************* public ********************/

/* 根据name取得frame */
Win.getFrame = function(name){
	return window.frames[name];
}

/* 刷新 frame */
/* param key[,url] */
Win.reloadFrame = function(){
	var args = arguments;
	if (args.length==1){
		getFrame(args[0]).location.reload();
	}else if (args.length==2){
		getFrame(args[0]).location.reload(args[1]);
	}
}


var BeanUtil = {};

BeanUtil.sortBeans = function(array, orderBy, asc){
	var ascn = asc?1:-1;
	var sortfunction = function(bean1, bean2){
		var p1 = bean1[orderBy];
		var p2 = bean2[orderBy];
		p1 = p1||"";
		p2 = p2||"";
		if(p1==p2){
			return 0;
		}
		var b = p1>p2 ? 1 : -1;
		return b * ascn;
	}
	return array.sort(sortfunction);
}

BeanUtil.getPropertyArray = function(list, property){
	var result = new Object(list.length);
	for(var i=0; i<list.length; i++){
		var e = list[i];
		result.push(e[property]);
	}
	return result;
}

BeanUtil.maxObj = function(list, property){
	var obj = null;
	for(var i=0; i<list.length; i++){
		var e = list[i];
		if(obj==null || obj[property]<e[property]){
			obj = e;
		}
	}
	return obj;
}

BeanUtil.maxProperty = function(list, property){
	var obj = MathUtil.maxObj(list, property);
	return obj[property];
}

BeanUtil.maxProperties = function(list, properties){
	if(arguments<2){
		return null;
	}
	var maxValMap = new Object();
	var pps = arguments.slice(1);
	for(var i=0; i<list.length; i++){
		var e = list[i];
		for(var j=0; j<pps.length; j++){
			var pName = pps[j];
			var pVal = e[pName];
			if(!maxValMap[pName] || maxValMap[pName]<pVal){
				maxValMap[pName] = pVal;
			}
		}
	}
	return maxValMap;
}

BeanUtil.listToMap = function(list, uniqueKey){
	var map = {};
	for(var i=0; i<list.length; i++){
		var e = list[i];
		var uniqueVal = e[uniqueKey];
		if(map[uniqueVal]){
			throw '属性不唯一！'+uniqueKey+'='+uniqueVal;
		}
		map[uniqueVal] = e;
	}
	
	return map;
}

BeanUtil.copyProperties = function(source, target){
	for(name in source){
		target[name] = source[name];
	}
}

if(typeof(Browser)=='undefined'){
	Browser = {};
}

Browser.getHashParamMap=function(){
	var qstr = location.hash.substr(1);
	var map = StringUtil.getUrlParamMap(qstr);
	return map;
}

Browser.setHashParamMap=function(map){
	var newQstr = StringUtil.getUrlParamStr(map);
	if(newQstr){
		location.hash = newQstr;
	}
}

Browser.getHashParam=function(name){
	var qstr = location.hash.substr(1);
	var map = StringUtil.getUrlParamMap(qstr);
	return map[name];
}

Browser.setHashParam=function(name, value){
	var qstr = location.hash.substr(1);
	var map = StringUtil.getUrlParamMap(qstr);
	map[name] = value;
	var newQstr = StringUtil.getUrlParamStr(map);
	location.hash = newQstr;
}

Browser.getUrlParamMap=function(){
	var qstr = location.search.substr(1);
	var map = StringUtil.getUrlParamMap(qstr);
	return map;
}
Browser.getUrlParam=function(name){
	var map = Browser.getUrlParamMap();
	return map[name];
}

Browser.getCookie=function(name){
	var cookies = document.cookie;
	if(cookies==null || cookies.length<1){
		return '';
	}
	var reg = new RegExp("\s*;?"+ name +"=([^;]*)(;|$)");
	r = cookies.match(reg);
	return r==null?r:r[1];
}

Browser.disableContextMenu = function(enable){
	if(!enable){
		document.oncontextmenu = new Function("return false");
	}else{
		document.oncontextmenu = null;
	}
}

Browser.getInfo = function(){
	var userAgent = navigator.userAgent,
	rMsie = /(msie\s|trident.*rv:)([\w.]+)/,
	rChrome = /(chrome)\/([\w.]+)/,
	rFirefox = /(firefox)\/([\w.]+)/,
	rOpera = /(opera).+version\/([\w.]+)/,
	rSafari = /version\/([\w.]+).*(safari)/;
	var browser;
	var version;
	function uaMatch(ua) {
	    var match = rMsie.exec(ua);
	    if (match != null) {
	        return {
	            browser: "IE",
	            version: match[2] || "0"
	        };
	    }
	    var match = rFirefox.exec(ua);
	    if (match != null) {
	        return {
	            browser: match[1] || "",
	            version: match[2] || "0"
	        };
	    }
	    var match = rOpera.exec(ua);
	    if (match != null) {
	        return {
	            browser: match[1] || "",
	            version: match[2] || "0"
	        };
	    }
	    var match = rChrome.exec(ua);
	    if (match != null) {
	        return {
	            browser: match[1] || "",
	            version: match[2] || "0"
	        };
	    }
	    var match = rSafari.exec(ua);
	    if (match != null) {
	        return {
	            browser: match[2] || "",
	            version: match[1] || "0"
	        };
	    }
	    if (match != null) {
	        return {
	            browser: "",
	            version: "0"
	        };
	    }
	}
	var browserMatch = uaMatch(userAgent.toLowerCase());
	if (browserMatch.browser) {
	    browser = browserMatch.browser;
	    version = browserMatch.version;
	}
	return {name:browser, version:version};
}

Browser.detectFlashVersion = function(){
    var ua = navigator.userAgent.toLowerCase();  
    var flash_version = 0;  
      
    if (navigator.plugins && navigator.plugins.length) {  
        var p = navigator.plugins['Shockwave Flash'];  
          
        if (typeof p == 'object') {  
            for (var i = 10; i >= 3; i--) {
                if (p.description && p.description.indexOf(' ' + i + '.') != -1) { flash_version = i; break; }  
            }  
        }  
    }  
    else if (ua.indexOf("msie") != -1 && ua.indexOf("win")!=-1 && parseInt(navigator.appVersion) >= 4 && ua.indexOf("16bit")==-1)  {  
        for (var i = 10; i >= 2; i--) {  
            try {  
                var object = eval("new ActiveXObject('ShockwaveFlash.ShockwaveFlash." + i + "');");  
                if (object) {  
                    flash_version = i; 
                    break;  
                }  
            }  
            catch (e) {}  
        }  
    }  
    else if (ua.indexOf("webtv/2.5") != -1) flash_version = 3;  
    else if (ua.indexOf("webtv") != -1) flash_version = 2;  
  
    return flash_version;  
}

var EventUtil = {};

EventUtil.addListEvent = function(elementList, event, fun){
	for(var i=0;i<elementList.length;i++){
		EventUtil.addEvent(elementList[i], event, fun);
	}
}

EventUtil.addEvent = function(element, event, fun){
	if(typeof(element)=='string'){
		element = $E(element);
	}
	if(!element){
		return;
	}
	if (element.addEventListener){//W3C DOM
		 element.addEventListener(''+event, fun, false);     
	}else if (element.attachEvent) {//IE
		 element.attachEvent('on'+event, fun);
	}else{
		element["on" + type] = fun;
	}
}

EventUtil.removeEvent = function(oTarget, sEventType, funName) {
	if (oTarget.removeEventListener) {// for DOM;
		oTarget.removeEventListener(sEventType, funName, false);
	} else if (oTarget.detachEvent) {
		oTarget.detachEvent("on" + sEventType, funName);
	} else {
		oTarget["on" + sEventType] = null;
	}
};

//注册全局事件
EventUtil.register = function(eventName, eventHandle, key){
	if(!key){
		key = this._keySeq?(this._keySeq++):(this._keySeq=1);
	}
	if(!this.eventMap){
		this.eventMap = {};
	}
	var funMap = this.eventMap[eventName];
	if(!funMap){
		funMap = {};
		this.eventMap[eventName] = funMap;
		var fun = function(e){
			EventUtil._handle(eventName, e);
		}
		var topElement = document.documentElement;
		EventUtil.addEvent(topElement, eventName, fun);
		EventUtil.addEvent(top.document.documentElement, eventName, fun);
	}
	funMap[key] = eventHandle;
}

EventUtil.unregister = function(eventName, key){
	if(!this.eventMap){
		return;
	}
	var funMap = this.eventMap[eventName];
	if(!funMap){
		return;
	}
	delete funMap[key];
}

EventUtil._handle = function(eventName, e){
	var funMap = this.eventMap[eventName];
	for(var name in funMap){
		var fun = funMap[name];
		fun.call(document.body, e);
	}
}

EventUtil.stopPropagation = function(e){
	e = e||window.event;
	if(document.all)
		e.cancelBubble=true;
	else 
		e.stopPropagation();
}

var ________________________________________;

var Ajax = {};

Ajax.sendHttpRequest = function(url, params, callback, method, cache){
	if(typeof(MooTools)!='undefined'){
		Ajax._mootools(url, params, callback, method, cache);
	}else if(typeof(jQuery)!='undefined'){
		Ajax._jquery(url, params, callback, method, cache);
	}else{
		Ajax._my(url, params, callback, method, cache);
	}
}

Ajax._my = function(url, params, callback, method, cache){
	if(!cache && params){
		params['_'] = ((new Date()).getTime());
	}
	var qstr = StringUtil.getUrlParamStr(params);
	var httpRequest = this._getHttpRequest();
	httpRequest.onreadystatechange = processStateChange;
	if(method=='POST' || (!method && qstr.length>256)){
		httpRequest.open("POST", url, true);
		httpRequest.setRequestHeader("Content-Length",qstr.length);  
		httpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
		httpRequest.send(qstr);  
	}else{
		var getUrl = url+(qstr ? (url.indexOf('?')==-1?'?':'&')+qstr : '');
		httpRequest.open("GET", getUrl, true);
		httpRequest.send(null);
	}
	
	function processStateChange() {
		if (httpRequest.readyState == 4) {// 4 = "loaded"
			if (httpRequest.status == 200) {// 200 = OK
				var serverDate = httpRequest.getResponseHeader('Date');
				callback(true, httpRequest.responseText);
			} else {
				callback(false, null, httpRequest.status, httpRequest);
			}
		}
	}
}

Ajax._getHttpRequest = function(){
	if(window.XMLHttpRequest){
		if(typeof(XMLHttpRequest)=='function'){
			return new XMLHttpRequest();
		}else{
			return window.XMLHttpRequest;	
		}
	}
	var msxmls = ["MSXML3", "MSXML2", "Microsoft"];
	for (var i=0; i < msxmls.length; i++) {
		try {
			return new ActiveXObject(msxmls[i]+".XMLHTTP");
		} catch (e) { }
	}
	throw new Error("No XMLHTTP component installed!");
}

Ajax._mootools = function(url, params, callback, method, cache){
	var myRequest = new Request({
		url:url, method:method||'get',
		onSuccess: function(responseText, responseXML){
			if(callback){
				callback(true, responseText);
			}
		},
		onFailure: function(req){
			if(callback){
				callback(false, req);
			}
		},
		onException: function(headerName, value){
			if(callback){
				callback(false, headerName+'='+value);
			}
		}
	});
	if(!cache){
		params['_'] = ((new Date()).getTime());
	}
	myRequest.send({'data':params});
}

Ajax._jquery = function(url, params, callback, method, cache){
	var options = {
		'url':url,
		'type':method||'GET',
		'data':params,
		'dataType': "text",
		'success':function(responseText, status, jqXHR){
			if(callback){
				callback(true, responseText, status, jqXHR);
			}
		},
		'error':function(jqXHR, status, error){
			if(callback){
				callback(false, error, status, jqXHR);
			}
		},
		'cache':(cache==true)
	};
	$.ajax(options);
}

var Dialog = {};

Dialog.load = function(url, title, width, containerId, callback){
	var onDownload = function(success, responseText){
		var e = $E(containerId)||DomUtil.newElement('DIV', {id:containerId, style:'display:none'}, containerId);
		e.innerHTML = responseText;
		Dialog.open(e, title, width);
		if(callback){
			callback();
		}
	}
	Ajax.sendHttpRequest(url, {}, onDownload, 'get', true);
}

Dialog.popupDiv = function(id, e){
	this._currentPopupDivId = id;
	var div = $E(id);
	div.setAttribute('class', 'popupMenu');
	div.style.display = '';
	if(!e){
		Effect.center(popDiv);
	}
	div.style.left = (e.clientX+'px');
	div.style.top = (e.clientY+'px');
}

Dialog.unpopupDiv = function(){
	var div = $E(this._currentPopupDivId);
	if(div){
		div.style.display = 'none';
	}
}

Dialog.open = function(viewElement, title, width, buttons){
	if(typeof(viewElement)=='string'){
		viewElement = $E(viewElement);
	}
	Effect.mask();
	var popDivId = (this._popDivId=this._popDivId||'_popDiv_'+new Date().getTime());
	var popDiv = $E(popDivId);
	if(!popDiv){
		var sHtml=''
			+'<div id="'+popDivId+'" class="popupDialog"'+(!width?'':'style="width:'+width+'px"')+'>'
			+'	<div class="pop_title_bar">'
			+'		<div class="pop_close_button">×</div>'
			+'		<div class="pop_title"></div>'
			+'	</div>'
			+'	<div class="pop_container">'
			+'	</div>'
			+'	<div class="cb"></div>'
			+'	<div class="pop_btnbar">'
			+'	</div>'
			+'</div>'
			+'';
		document.body.insertAdjacentHTML('AfterBegin', sHtml);
		popDiv = $E(popDivId);
		var titlebar = DomUtil.getChild(popDiv,'class','pop_title_bar');
		
		Effect.drag(popDiv, null, titlebar);
		
		var closeButton = DomUtil.getChild(titlebar,'class','pop_close_button');
		EventUtil.addEvent(closeButton, 'click', function(){Dialog.close();});
		EventUtil.register('keydown', function(e){if(e.keyCode==27)Dialog.close();}, 'pop_close');
	}

	//buttons
	var btnbar = DomUtil.getChild(popDiv,'class','pop_btnbar');
	DomUtil.removeChildren(btnbar);
	
	if(buttons){
		for(var name in buttons){
			var fun = buttons[name];
			var btn = DomUtil.newElement('input', {type:'button', value:name}, btnbar);
			btn.onclick = fun;
		}
	}
	
	popDiv.style.display='';
	
	var children = DomUtil.getChildren(popDiv);
	var container = children[1];
	
	var oldViewElement = DomUtil.getChild(container);
	if(oldViewElement){
		if(oldViewElement.id){
			oldViewElement.style.display='none';
			document.body.insertAdjacentElement('AfterBegin', oldViewElement);
		}else{
			container.removeChild(oldViewElement);
		}
	}

	viewElement.style.display='';
	container.appendChild(viewElement);
	
	var titlebar = children[0];
	var titleLabel = DomUtil.getChild(titlebar, 'class','pop_title');
	titleLabel.innerHTML = title;
	
	Effect.center(popDiv, null, 200);
}

Dialog.close = function(){
	$E(this._popDivId).style.display='none';
	Effect.unmask();
}

var _______________________________________;

/*效果*/
var Effect = {};

Effect.mask = function(){
	var newMask = document.createElement("div");
	newMask.id = '_wjg_mask_';
	newMask.style.position = "absolute";
	newMask.style.zIndex = 98;
	_scrollWidth = Math.max(document.body.scrollWidth,document.documentElement.scrollWidth);
	_scrollHeight = Math.max(document.body.scrollHeight,document.documentElement.scrollHeight);
	_scrollHeight = Math.max(_scrollHeight,document.documentElement.clientHeight);
	newMask.style.width = _scrollWidth + "px";
	newMask.style.height = _scrollHeight + "px";
	newMask.style.top = "0px";
	newMask.style.left = "0px";
	newMask.style.background = "#000000";
	newMask.style.filter = "alpha(opacity=50)";
	newMask.style.opacity = "0.4";
	newMask.onkeydown=newMask.onclick=function(e){
		if(document.all)
			window.event.cancelBubble=true;
		else 
			e.stopPropagation();
	}
	document.body.appendChild(newMask);
}

Effect.unmask = function(){
	var id = '_wjg_mask_';
	var e = document.getElementById(id);
	if(e){
		e.parentNode.removeChild(e);
	}
}

Effect.center = function(element, x, y){
	var x2 = (Win.width()-element.offsetWidth)/2;
	var y2 = (Win.height()-element.offsetHeight)/2;
	x = x ? Math.min(x, x2) : x2;
	y = y ? Math.min(y, y2) : y2;
	element.style.left = x+'px';
	element.style.top = y+'px';
}

/**
	*拖动
	*@param o 被拖动的对象或对象id
*/
Effect.drag = function(o,s,b){
	if (typeof(o)== "string"){
		o = document.getElementById(o);
	}
	o.orig_x = parseInt(o.style.left) - document.body.scrollLeft;
	o.orig_y = parseInt(o.style.top) - document.body.scrollTop;
	o.orig_index = o.style.zIndex;
	o.onmousedown = function(e){
		this.style.zIndex = 800;
		var doc = document;
		if(!e)e = window.event;
		var src = e.target||e.srcElement;
		
		if(b && !DomUtil.isSuper(b, src)){
			return;
		}
		
		var x = e.clientX+doc.body.scrollLeft-o.offsetLeft;
		var y = e.clientY+doc.body.scrollTop-o.offsetTop;
		doc.ondragstart = "return false;" ;
		doc.onselectstart = "return false;" ;
		doc.onselect = "document.selection.empty();" ;
		if(o.setCapture)
			o.setCapture();
		else if(window.captureEvents)
			window.captureEvents(Event.MOUSEMOVE|Event.MOUSEUP);
		doc.onmousemove = function(e){
			if(!e)e = window.event;
			o.style.left = e.clientX+document.body.scrollLeft-x+"px";
			o.style.top = e.clientY+document.body.scrollTop-y+"px";
			o.orig_x = parseInt(o.style.left) - document.body.scrollLeft;
			o.orig_y = parseInt(o.style.top) - document.body.scrollTop;
		}
		doc.onmouseup = function(){
			if(o.releaseCapture)
			o.releaseCapture();
			else if(window.captureEvents)
				window.captureEvents(Event.MOUSEMOVE|Event.MOUSEUP);
			doc.onmousemove = null;
			doc.onmouseup = null;
			doc.ondragstart = null;
			doc.onselectstart = null;
			doc.onselect = null;
			o.style.zIndex = o.orig_index;
		}
	}
	if (s){
		var orig_scroll = window.onscroll?window.onscroll:function (){};
		window.onscroll = function (){
			orig_scroll();
			o.style.left = o.orig_x + document.body.scrollLeft+"px";
			o.style.top = o.orig_y + document.body.scrollTop+"px";
		}
	}
}

if(typeof(FormUtil)=='undefined'){
	FormUtil = {};
}

FormUtil.sortSelect = function(obj, fromIndex){
	var fromIndex = fromIndex||0;
	var selObj = typeof(obj)!="string" ? obj:document.getElementById(obj);
	var so = selObj.options;
	var oa = [];
	for(var i=fromIndex; i<so.length; i++){
		oa.push(so[i]);
	}
	sortBeans(oa, 'text', true);
	
	selObj.options.length = fromIndex;
	for(var i=0; i<oa.length; i++){
		selObj.options.add(oa[i]);
	}	
}

/* 检查select是否包含文本 */
/* [select] [,value] */
FormUtil.checkSelectValue = function(){
	var args = arguments;
	if (args.length>=2)	{
		var opts = args[0].options;
		var v = args[1];
		for(i=0;i<opts.length;i++){
			if (opts[i].value==v)
				return i;
		}
	}
	return -1;
}

/* 检查select是否包含文本 */
/* [select] [,text] */
FormUtil.checkSelectText = function(){
	var args = arguments;
	if (args.length>=2)	{
		var opts = args[0].options;
		var v = args[1]; 
		for(i=0;i<opts.length;i++){
			if (opts[i].text==v)
				return i;
		}
	}
	return -1;
}

//选中指定值的选项
FormUtil.selectByValue = function(){
	var args = arguments;
	if (args.length>=2){
		var sel = args[0];
		var v = args[1];
		var opts = sel.options;
		for(i=0;i<opts.length;i++){
			if (opts[i].value==v){
				sel.selectedIndex=i;
				return i;
			}
		}
	}
	return -1;
}

FormUtil.setAllCheckBox = function(checkboxList, checked){
	if(typeof(checkboxList)=='string'){
		checkboxList = document.getElementsByName(checkboxList);
	}
	for(var i=0;i<checkboxList.length;i++){
		checkboxList[i].checked = (checked==true);
	}
}

//关键事件(全选)
FormUtil.associateCheckBox = function(checkboxAll, checkbox){
	checkboxAll = document.getElementById(checkboxAll);
	checkboxList = document.getElementsByName(checkbox);
	checkboxAll.onclick = function(){FormUtil.setAllCheckBox(checkboxList, this.checked)};
	function onCheckBoxClick(){
		var v = FormUtil.getInputValue(checkbox);
		checkboxAll.checked = !(!v);
	}
	for(var i=0;i<checkboxList.length;i++){
		EventUtil.addEvent(checkboxList[i], 'click', onCheckBoxClick);
	}
}

var Widget = {};

Widget.getView = function(value, format){
	if(!value){
		return '';
	}
	if(format=='date'){
		var date = new Date(value);
		return StringUtil.getFormatDate(date);
	}
	return value;
}

Widget.getInput = function(name, format){
	if(!name){
		return '';
	}
	if(format=='date'){
		var shtml = '<input name="'+name+'" class="Wdate" value="" onclick="WdatePicker({dateFmt:\'yyyy-MM-dd HH:mm\'})" />';
		return shtml;
	}else if(format=='switch'){
		var shtml = '<select name="'+name+'">'
			+'<option value="N">否</option>'
			+'<option value="Y">是</option>'
			+'</select>';
		return shtml;
	}
	return name;
}

//////////////////////////////////////////////////////////////////////
/* 
	firefox 没有insertAdjacentElement()，使用以下代码解决 
*/

if(typeof HTMLElement!="undefined" && !HTMLElement.prototype.insertAdjacentElement){
     HTMLElement.prototype.insertAdjacentElement = function(where,parsedNode){
        switch (where){
            case 'BeforeBegin':
                this.parentNode.insertBefore(parsedNode,this);
                break;
            case 'AfterBegin':
                this.insertBefore(parsedNode,this.firstChild);
                break;
            case 'BeforeEnd':
                this.appendChild(parsedNode);
                break;
            case 'AfterEnd':
                if (this.nextSibling) this.parentNode.insertBefore(parsedNode,this.nextSibling);
                    else this.parentNode.appendChild(parsedNode);
                break;
         }
     }

     HTMLElement.prototype.insertAdjacentHTML = function (where,htmlStr){
         var r = this.ownerDocument.createRange();
         r.setStartBefore(this);
         var parsedHTML = r.createContextualFragment(htmlStr);
         this.insertAdjacentElement(where,parsedHTML);
         return parsedHTML;
     }

     HTMLElement.prototype.insertAdjacentText = function (where,txtStr){
         var parsedText = document.createTextNode(txtStr);
         this.insertAdjacentElement(where,parsedText);
     }
}

/*
	这是根据firefox中默认把event对象作第一个参数传递给事件处理函数的特点而写的hack
*/
/*
//貌似不好使
if(window.Event){
 window.constructor.prototype.__defineGetter__("event", function(){
  var o = arguments.callee.caller;
  var e;
  while(o != null){
   e = o.arguments[0];
   if(e && (e.constructor == Event || e.constructor == MouseEvent)){
		e.srcElement=e.target;
		return e;
   }
   o = o.caller;
  }
  return null;
 });
}
*/
//////////////////////////////////////////////////////////////////

window.top.document.onkeydown=document.onkeydown=function(event){
	var event = window.event||arguments[0];
	if(event.keyCode==27||event.keyCode==116){
		//event.keyCode = 0;
		event.cancelBubble = true;
		event.returnValue = false;
	}
}

function getSelectedHtml() {
	var html = "";
	if (window.document.selection && window.document.selection.createRange) {
		var rng = window.document.selection.createRange();
		html = rng.htmlText;
	} else if (window.getSelection) {
		var rng = window.getSelection();
		if (rng.rangeCount > 0 && window.XMLSerializer) {
			rng = rng.getRangeAt(0);
			html = new XMLSerializer().serializeToString(rng.cloneContents());
		}
	}
	return html;
}

function GetFireFoxInnerHTML(nodes) {
	var result = '';
	var node;
	for ( var i = 0; i < nodes.length; i++) {
		node = nodes[i];
		if (node.nodeValue)
		// 纯文本节点还原。
		{
			result += node.nodeValue;
		} else if (node.tagName) {
			result += "<" + node.tagName;
			if (node.innerHTML) {
				// 属性还原。
				if (node.attributes && node.attributes.length > 1) {
					for ( var j = 0; j < node.attributes.length - 1; j++) // 忽略最后一个，最后一个是FirFox自己的节点。
					{
						result += ' ' + node.attributes[j].name + "='"
								+ node.attributes[j].value + "'";
					}
				}
				result += ">" + node.innerHTML + "</" + node.tagName + ">";
			} else {
				result += " />";
			}
		}
	}
	return result;
}


